<?php

namespace app\api\service\intelligentlive;

use app\api\model\intelligentlive\Products;
use app\lib\exception\intelligentlive\IntelligentliveException;
use think\Db;
use think\Exception;
use think\Request;

class ProductsService
{
    private static $instance;

    public static function getInstance(): ProductsService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function addProducts($params)
    {
        $i = 0;
        foreach ($params as $item) {
            $product = Products::where("product_id",$item['product_id'])->findOrEmpty();
            if (!$product->isEmpty()){
                continue;
            }
            Db::startTrans();
            try {
                $res = Products::create($item);
                if ($res) {
                    $i += 1;
                }
                DB::commit();
            }catch (Exception $e){
                // 回滚事务
                Db::rollback();
                throw new IntelligentliveException([
                    'msg' => '新增失败',
                    'error_code' => 20002
                ]);
            }
        }
        return "新增".$i."条数据";
    }

    public function productsList($params)
    {
        $pageSize = $params['pageSize']??200;
        $query = Products::field("*");
        if (!empty($params["product_name"])) {
            $query->where('product_name',"like","%".$params['product_name']."%");
        }
        if (!empty($params["query_info"])) {
            $query->where('query_info',"like","%".$params['query_info']."%");
        }
        $order = "";
        foreach ($params["info"] as $key=>$val) {
            if ($val != 0) {
                $sc = $val==1?'asc':'desc';
                $order = $key." ".$sc;
                break;
            }
        }
        if ($order != "") {
            $query->order($order);
        }
        $data = $query->paginate($pageSize);
        return $data;
    }
}